import re
import sys
import traceback
import subprocess
from gravityassist.musiclib import get_music_list

music_regex = '( - VLC media player|_哔哩哔哩_bilibili — Mozilla Firefox)$'

def current_music():
    if sys.platform != 'linux':
        return {'playing': False}
    try:
        with subprocess.Popen(['wmctrl', '-l'], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as p:
            stdout, _ = p.communicate()
            stdout = stdout.decode()
            title = ''
            for line in stdout.splitlines():
                # 0x02000003  3 archer 终端
                m = re.match(r'^0x([0-9a-f]+)\s+(\d+)\s+(.*?)\s+(.*)$', line)
                if m:
                    title = m.group(4).strip()
                if re.search(music_regex, title):
                    break
            else:
                title = ''
        if title:
            title = re.sub(music_regex, '', title)
        title = title.strip()
        if title.endswith('.mp4'):
            title = title[:-len('.mp4')]
        if not title:
            return {'playing': False}
        music_list = get_music_list()
        for i, music in enumerate(music_list):
            if music["name"] == title:
                return {'playing': True, 'name': title, 'id': i, 'path': music["path"]}
        return {'playing': True, 'name': title}
    except:
        traceback.print_exc()
        return {'playing': False}
